package com.chushouya.common.util;

import com.chushouya.common.config.CaptchaProperties;
import com.general.framework.core.enums.LoginCodeEnum;
import com.wf.captcha.*;
import com.wf.captcha.base.Captcha;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.awt.*;
import java.util.Objects;

/**
 * 图形验证码
 */
@Slf4j
public class CaptchaUtil {

    /**
     * 获取验证码生产类
     * @return /
     */
    public static Captcha getCaptcha() {
        CaptchaProperties captchaProperties = new CaptchaProperties();
        captchaProperties.setLength(4);
        if (Objects.isNull(captchaProperties.getCodeType())) {
            captchaProperties.setCodeType(LoginCodeEnum.spec);
        }
        return switchCaptcha(captchaProperties);
    }

    /**
     * 依据配置信息生产验证码
     * @param captchaProperties 验证码配置信息
     * @return /
     */
    private static Captcha switchCaptcha(CaptchaProperties captchaProperties) {
        // https://gitee.com/whvse/EasyCaptcha
        Captcha captcha = null;
        switch (captchaProperties.getCodeType()) {
            case arithmetic:
                // 算术类型
                captcha = new ArithmeticCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
                // 几位数运算，默认是两位
                captcha.setLen(captchaProperties.getLength());
                break;
            case chinese:
                captcha = new ChineseCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
                captcha.setLen(captchaProperties.getLength());
                break;
            case chinese_gif:
                captcha = new ChineseGifCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
                captcha.setLen(captchaProperties.getLength());
                break;
            case gif:
                captcha = new GifCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
                captcha.setLen(captchaProperties.getLength());
                break;
            case spec:
                captcha = new SpecCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
                captcha.setLen(captchaProperties.getLength());
                break;
            default:
                log.error("配置异常");
        }
        if(StringUtils.isNotBlank(captchaProperties.getFontName()) ){
            captcha.setFont(new Font(captchaProperties.getFontName(), Font.PLAIN, captchaProperties.getFontSize()));
        }
        return captcha;
    }
}
